<template>
    <view class="page-body" v-if="isShowListPage" :class="{ bodyFixed: isBodyFixed }">
        <swiper v-if="isBananerData" class="page-slide-bananer" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular="true">
            <swiper-item v-for="(item,index) in listImg.list" :key="index">
                <view class="slide-bananer-item">
                    <image :src="item.image" mode="scaleToFill" @tap="openBananer(item.id)"></image>
                </view>
            </swiper-item>
        </swiper>
        <view v-show="!isSearchflxed" class='search-release-box' >
            <Search placeholder="搜索货物" @resultMethod="searchData" searchKey="goodsName"
                    remoteUrl="/wechat/demand/listDemands"></Search>
            <view class="release-btn">
                <button type="" @tap="onReleaseDemand">发布求购</button>
            </view>
        </view>
				<view v-show="isSearchflxed" class='search-release-box-flxed'>
						<Search placeholder="搜索货物" @resultMethod="searchData" searchKey="goodsName"
										remoteUrl="/wechat/demand/listDemands"></Search>
						<view class="release-btn">
						  		<button type="" @tap="onReleaseDemand">发布求购</button>
							
						</view>
				</view>
        <view  :class="isBananerData? 'page-list-flxed' : 'page-list' ">
            <!-- 列表组件 -->
            <block v-for="(item,index) in resData.list" :key="index">
                <trade-item :data="item" :params="params" @OnQuote="OnQuote" 
                            :optionMethod="callQoute" infoIcon="../../static/ibs/img_comm_closed.png"></trade-item>
            </block>
        </view>
		<view class="no-data" v-if="searchNoData || noData">
				<image class="no-data-image" src="../../static/ibs/img_home_empty.png" mode=""></image>
				<view class="no-data-text" >暂无求购信息</view>
		</view>
        <!-- 加载更多组件 -->
        <load-more v-if="!searchNoData && !noData" :loadingType="loadingType" :showImage="showImage" :contentText="contentText">{{searchNoData}}
        </load-more>
        <!-- 完善资料框 -->
        <information-box class="isShowInfoBox-index" @closeInfo="closeInfo" :id="demandId" :infoType="infoType" remoteUrl="/wechat/user/saveUser"
                         :title="info" v-if="isShowInfoBox"></information-box>
        <!-- 报价弹层 -->
        <quote-box v-if="isShowQuoteBox" @closeInfo="closeInfo" :id="demandId"
                   remoteUrl="/wechat/demand/addQuote"></quote-box>
        <!-- 支付弹层 -->
        <pay-box v-if="isShowpayBox" @closeInfo="closeInfo" :unreadQuote="unreadQuote" :demandInfo="demandInfo"
                 remoteUrl="/wechat/demand/unifiedOrder"></pay-box>
        <!-- 支付成功弹层 -->
        <pay-success v-if="isShowpaySuccessBox" @closeInfo="closeInfo" :paySuccessInfo="paySuccessInfo"></pay-success>

    </view>
</template>
<script>
    import Search from '@/components/search/search.vue'; //搜索组件
    import tradeItem from '@/components/ibs/tradeItem.vue';
    import loadMore from '@/components/loadMore.vue'  //调用列表上拉更新数据组件
    import informationBox from '@/components/form/informationBox.vue'  //完善信息弹层
    import quoteBox from '@/components/form/quoteBox.vue'  //报价弹层
    import payBox from '@/components/form/pay.vue'  //报价弹层
    import paySuccess from '@/components/form/paySuccess.vue'  //报价弹层
    import api from '@/common/api.js';   //请求API方法
    import sysEnum from '@/common/sysEnum.js';
    import publicMethod from '@/common/publicMethod.js';
    import {wxSetting, wxAuthorize} from '../../common/wxApi.js';

    export default {
        components: {
            tradeItem,
            loadMore,
            informationBox,
            quoteBox,
            Search,
            payBox,
            paySuccess

        },
        onPullDownRefresh() {
            this.noData = false;
            this.loadingType = 0;
            this.getData();
        },
        onReachBottom() {
            if (this.loadingType !== 0) {
                return;
            }
            this.loadingType = 1;
            setTimeout(() => {
                this.addData();
            }, 1200);
        },
        data() {
            return {
                searchValue: null, //搜索值
                isShowClear: false,  //清除按钮
                showImage: false,  //加载更多图片
                loadingType: 0,    //加载更多状态值
				noData: false,    //列表数据状态值
				searchNoData: false,  //搜索列表状态值
                isShowInfoBox: false,  //完善资料框
                isShowQuoteBox: false, //报价弹层
                isShowpaySuccessBox: false, //报价成功状态值
                demandId: false, //报价ID
                demandInfo: {},  //求购信息
                isShowpayBox: false, //微信支付弹窗
                isShowListPage: false, //是否显示列表页
                unreadQuote: null,  //未读报价
                paySuccessInfo: null, //支付成功后返回的信息
				isBananerData: false,  //是否轮播图标识
				infoType: null,   //资料填写完，弹出框的类型 1:报价弹窗口  2:求购页面
                systemInfo: {        //系统初始界面信息值
                    windowWidth: 0,
                    windowHeight: 0,
                    pixelRatio: 0
                },
                info: {
                    titleRow1: '为了卖家能联系您',
                    titleRow2: '请在求购前留下您的联系方式'
                },
                contentText: {
                    contentdown: "",
                    contentrefresh: "正在加载...",
                    contentnomore: ""
                },
                currentScrollTop: 0,  //当前滚条离头部的高度值
                isSearchflxed: false,
                bannerHeight: 346,    //轮播图片高度 指的是upx
                resData: {    //数据列表值
                    pageNum: 1,
                    total: 0,
                    list: []
                },
                listImg: {    
                    list: []
                },
                params: [
                    {
                        label: '采购意向价格',
                        key: 'intentPrice'
                    },
                    {
                        label: '买家联系方式',
                        key: 'contactMobileNo'
                    },
                    {
                        label: '要求',
						labelClass:['label-flex-start'],
						valueClass:['default-value-class','value-fix'],
                        key: 'remarkDemand'
                    }
                ],
//				optionMethod: this.callQoute,
                shareDemanId: null ,// 分享的求购ID,
				isBodyFixed:false //解决 弹窗后滚动穿透

            };
        },

        onLoad(option) {
			let that = this;
            //	wxApi.wxSetting();
			var isUserInfo=that.isGetWxUserInfo(); //判断用户是否获取
				if (option && option.id) {
				    this.shareDemanId = option.id;
				}
				if(isUserInfo){
					that.getBannerData(); //图片轮播初始化
				    that.onWebSocket();    //websocket调用方法
				}else{
					that.loginSystem();    //登陆系统  
				}
				that.sysInfo();        //获取系统信息
        },
        onShow() {
            let that = this;
			var isUserInfo=that.isGetWxUserInfo(); //判断用户是否获取
			if(isUserInfo){
				that.getData();  //初始化数据
				that.initTabBarBadge(2);   //初始化小红点
			}
        },
        //页面滚动事件
        onPageScroll(e) {
            let that = this;
						
						console.log(e.scrollTop);
						if(e.scrollTop/2>110){
							that.isSearchflxed = true;
						}else{
							that.isSearchflxed = false;
						}
/* 			if(that.isBananerData){  //当存在banner图时才执行样式切换
				that.currentScrollTop = e.scrollTop * that.systemInfo.pixelRatio;
				if (that.currentScrollTop > 220) {
					
					that.isSearchflxed = true;
				} else {
					that.isSearchflxed = false;
				}
			} */
        },
        methods: {
			getScrollTop(){ // 获取滚动条位置
				var scrollTop=0;
				if(document.documentElement&&document.documentElement.scrollTop){
					scrollTop=document.documentElement.scrollTop;
				}else if(document.body){
					scrollTop=document.body.scrollTop;
				}
				return scrollTop;
			},
			 popUpEmptyClick() { // 点击弹窗空白处
			  this.isShowPopup = false;
			},
            //判断是否获取微信用户信息
            isGetWxUserInfo() {
                let that = this;
                var vxUserInfo = uni.getStorageSync(sysEnum.enums.USER.WX_USER_INFO);
                if (vxUserInfo) {
                    that.isShowListPage = true;
					return true
                }else{
					return false;
				}
            },
            //调用socket方法
            onWebSocket() {
                let that = this;
                var socketOpen = false;                //调用webSocket开关标识
                var socketMsgQueue = [];   		     //发送服务内容
                var sessionKey = uni.getStorageSync(sysEnum.enums.USER.SESSION_KEY); // 获取本地缓存的seeesionKey
                var url = conf.wsUrl+sessionKey;
                console.log("----------socket-----", url);
                uni.connectSocket({
                    url: url,    				 //调用webSocket 服务地址
                    header: {       				 //头部信息
                        'content-type': 'application/json'
                    },
                    method: 'GET',//请求方式
                    success(res) {
                    }
                });


                //打开调用webSocket
                uni.onSocketOpen(function (res) {
                    console.log('打开websocket连接成功');
                    //接受websocket消息数据
                    uni.onSocketMessage(function (res) {
                        if (res.data) {   //如果存在消息就显示小红点
						    that.$store.dispatch('update_unread_quote', true); // 缓存是否有报价信息
                            that.TabBarBadge(2, true);
                        } else {
							that.$store.dispatch('update_unread_quote', false); // 缓存是否有报价信息
                            that.TabBarBadge(2, false);
                        }
                    });
                });
            },
            //发送 websocket 消息数据
            sendSocketMessage1(msg) {
                if (socketOpen) {
                    uni.sendSocketMessage({
                        data: msg
                    });
                } else {
                    socketMsgQueue.push(msg);
                }
            },
            //获取页面基础信息
            sysInfo() {
                let that = this;
                uni.getSystemInfo({
                    success: function (res) {
                        that.systemInfo.windowWidth = res.windowWidth;
                        that.systemInfo.windowHeight = res.windowHeight;
                        that.systemInfo.pixelRatio = res.pixelRatio;
                    }
                });
            },
            /**
             * 搜索结果回调函数
             * @param data 搜索结果数据
             */
            searchData(data) {
                let that = this;
                that.searchValue = data;
                that.getData();
            },

            //初始化获取数据 及搜索访求
            getData() {
                let that = this;
				that.isBodyFixed = false;
                //调用请求数据方法
                var url = "/wechat/demand/listDemands";   //请求的URL
                var params = {
                    goodsName: that.searchValue,
                    id: that.shareDemanId
                };
                api.httpRequest(url, params, "POST").then((res) => {
                    that.resData.list = res.result.list;   //获取列表数据
                    that.resData.pageNum = res.result.pageNum;   //获取当前页
                    that.resData.total = res.result.total;  //获取总页数，加载更多会用到
                    if (that.searchValue == '' || that.searchValue==null ) {   //搜索条件不等于空的情况下，查询出来的数据，如果为空就跳转到初始页
                        if (res.result.total == 0) {   //如果列表就跳转到制作初始页
                            that.noData = true;
                        } else {
                            that.noData = false;
                            that.searchNoData = false;
                        }
                    } else {
                        if (that.resData.list == '' || that.resData.list.length === 0) {
                            that.searchNoData = true;
                        } else {
                            that.searchNoData = false;
                        }
                        that.noData = false;
                    }
                });
            },

            //获取轮播图
            getBannerData() {
                let that = this;
                //调用请求数据方法
                var url = "/wechat/home/links";   //请求的URL
                var params = {};
                api.httpRequest(url, params, "GET").then((res) => {
					if(res.result.length>0){    //如果存在轮播图就显示
						that.isBananerData=true;
						that.listImg.list = res.result;   //获取列表数据
						
					}else{
						that.isBananerData=false;
						that.isSearchflxed=true;
						
					}
                })
            },
            /*
                滑到最底部时触发（上拉更多）方法
            */
            async addData() {
                if (this.resData.list.length >= this.resData.total) {  //当前页面中的数据列表大于或者等于数据库中total时，直接返回
                    this.loadingType = 2;
                    return;
                } else {
                    this.loadingType = 1;  //状态加载中
                    var url = "/wechat/demand/listDemands";   //请求地址
                    var params = {
                        goodsName: this.searchValue,           //获取搜索的值
                        pageNum: this.resData.pageNum + 1    //传请求的页数,
                    };
                    await api.httpRequest(url, params, "post",true).then((res) => {
                        this.resData.list = this.resData.list.concat(res.result.list);
                        this.resData.pageNum = res.result.pageNum;
                        this.loadingType = 0;
                    });
                }
            },

            //点击发布求购按钮
            onReleaseDemand() {
                let that = this;
                let userInfo = that.$store.getters.getUserInfo; //从缓存获取用户的个人信息数据
                if (userInfo.contactName != '' && userInfo.contactName != null && userInfo.contactMobileNo != '' && userInfo.contactMobileNo != null) {
                    uni.navigateTo({
                        url: '/pages/demand/buyInfo'
                    });
                } else {
					that.infoType=2;
                    that.isShowInfoBox = true;
					this.isBodyFixed = true;//页面禁止滚动
                }
            },
			//清空搜索框数据
            clear() {
                let that = this;
                that.searchValue = null;
                that.isShowClear = false;
            },
            //关闭窗口
            closeInfo(val) {
                let that = this;
                if (val == "quoteBox") {
                    that.isShowQuoteBox = false; //关闭报价弹窗口
                } else if (val == "infoBox") {
                    that.isShowInfoBox = false; //关闭完善弹窗口				
                } else if (val == "payBox") {
                    that.isShowpayBox = false;  //关闭支付弹窗口
                } else if (val == "paySuccessBox") {
                    that.isShowpaySuccessBox = false;  //关闭支付成功弹窗口
                }
				this.isBodyFixed = false;//页面可以滚动
            },

            //报价弹窗
            OnQuote(data) {
                let that = this;
                let userInfo = that.$store.getters.getUserInfo; //从缓存获取用户的个人信息数据
				if(data.isSelf){
					uni.showToast({
						title: '这是您本人发布的求购!',
						icon: 'none',
						duration: 2000
					});
					
				}else{
					that.demandId = data.id;
					if (userInfo.contactName != '' && userInfo.contactName != null && userInfo.contactMobileNo != '' && userInfo.contactMobileNo != null) {
						that.isShowQuoteBox = true;
					} else {
						that.infoType=1;
						that.isShowInfoBox = true;
					}
					this.isBodyFixed = true;
				}
            },
            //查看信息弹窗
            OnseeInfo(data) {
                let that = this;
                that.isShowpayBox = true;
				this.isBodyFixed = true;
            },
            //查看报价
            callQoute(data) {
				let that = this;
				let userInfo = that.$store.getters.getUserInfo; //从缓存获取用户的个人信息数据
				if (userInfo.contactName != '' && userInfo.contactName != null && userInfo.contactMobileNo != '' && userInfo.contactMobileNo != null) {
					that.callQouteFn(data)
				} else {
					that.demandInfo=data;
					that.infoType=3;          
			        var url = '/wechat/demand/getMoney';
					var params = {};
					api.httpRequest(url, params, "GET").then((res) => {  //获取支付金额
					    that.unreadQuote = res.result;   //获取报价金额
					  	that.isShowInfoBox = true;
					   this.isBodyFixed = true;
					});
				}
            },
			openBananer(id){ // 查看轮播图详情
			 this.goTo('/pages/demand/homeLinke?id=' + id);
			}
        }
    }
</script>
<style>
    .page-body {
        background: #F2F2F5;
        width: 100vw;
        min-height: 100vh;
        padding-bottom: 20upx;
    }

    .page-body-box {
        background: #F2F2F5;
        margin-left: 24upx;
        margin-right: 24upx;
    }

    .page-slide-bananer {
        width: 100%;
        height: 400upx;
        background: #E5E5E5;
    }
	.page-slide-bananer .wx-swiper-dots.wx-swiper-dots-horizontal{
		 margin-bottom: 50rpx;
		 right: 10%;
		
	}
    .slide-bananer-item image {
        width: 100%;
        height: 400upx;
    }

    .search-release-box {
        display: flex;
        justify-content: space-between;
        height: 108upx;
        line-height: 108upx;
        margin-left: 24upx;
        margin-right: 24upx;
        background: #FFFFFF;
        margin-top: -54upx;
        z-index: 100;
        position: relative;
        align-items: center;
        border-radius: 15upx;
        border: 1upx solid #E5E5E5;
        width: 702upx;
    }

    .search-release-box .search-input-bg {
        border: 2upx solid #E5E5E5;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 68upx;
        line-height: 68upx;
        border-radius: 34upx;
        margin-left: 20upx;
        margin-right: 20upx;
        width: 482upx;
        padding-left: 20upx;
        padding-right: 20upx;
    }

    .search-release-box .search-input-bg image {
        width: 36upx;
        height: 36upx;
    }

    .search-release-box .search-input-bg input {
        font-size: 28upx;
        width: 100%;
        margin-left: 20upx;
    }

    .search-release-box-flxed {
        display: flex;
        justify-content: space-between;
        height: 108upx;
        line-height: 108upx;
        background: #FFFFFF;
        z-index: 100;
        position: fixed;
        align-items: center;
        top: 0;
        width: 100%;
    }

    .search-release-box-flxed .search-input-bg {
        border: 2upx solid #E5E5E5;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 68upx;
        line-height: 68upx;
        border-radius: 34upx;
        margin-left: 20upx;
        margin-right: 20upx;
        width: 542upx;
    }

    .search-release-box-flxed .search-input-bg image {
        width: 36upx;
        height: 36upx;
        padding-right: 20upx;
        padding-left: 20upx;
    }

    .search-release-box-flxed .search-input-bg input {
        font-size: 28upx;
        width: 100%;
    }

    .release-btn {
        height: 68upx;
        line-height: 68upx;
        padding-right: 20upx;
    }

    .release-btn button {
        font-size: 28upx;
        background: #077131;
        border-radius: 34upx;
        width: 160upx;
        padding: 0;
        color: #FFFFFF;
    }

    .page-list {
        width: 702upx;
        margin-left: 24upx;
        margin-right: 24upx;
        margin-bottom: 20upx;
    }
    .page-list-flxed {
        width: 702upx;
        margin-left: 24upx;
        margin-right: 24upx;
        margin-bottom: 20upx;
		padding-top: 110upx;
    }
    .switch-tab {
        width: 100%;
        height: 100%;
        background-color: #FFFFFF;
    }

    .isShowInfoBox-index {
        z-index: 1000;
    }

    .view-price {
        width: 100%;
        height: 112upx;
        flex-shrink: 0;
        margin-bottom: 9upx;
        text-align: left;
        display: flex;
        align-items: flex-end;

    }

    .info-button {
        width: 100upx;
        height: 48upx;
        line-height: 48upx;
        margin-left: 20upx;
        padding: 0 20upx;
        text-align: center;
        border-radius: 24upx;
        border: 2upx #077131 solid;
        color: #077131;
        font-weight: bold;
        font-size: 20upx;
        align-self: flex-end;
    }
	.no-data{
		text-align: center;
	
		font-size: 28upx;
		height: 100%;
		padding-top: 180upx;
	}
	.no-data-image{
		width: 200upx;
		height: 200upx;
	}
	.no-data-text{
		text-align: center;
		color: #000000;
		font-size: 32upx;
	}
	.bodyFixed{
		position:fixed;
		top:0;
		left:0;
		z-index:0;
	}
	.default-content-class .default-base-single .label-flex-start{
		align-self: flex-start;
		width:auto;
		-webkit-flex-shrink:0;
		flex-shrink:0;
		box-sizing:border-box;
		font-size:26rpx !important;
		color:#4c4c4c;
		text-align:left;
	}
	.default-content-class .default-base-single	.default-value-class.value-fix{
		box-sizing: border-box;
		padding-right:20upx;
		border-right:1upx solid #e6e6e6;
		position:relative;
		right:-1upx;
		text-align: justify;
	}

</style>
